/*  This file is part of the comicconquer project
    Copyright (C) 2010 Reach <reach334@gmail.com>

    ComicConquer is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This software is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    Lesser General Public License for more details.

    You should have received a copy of the GNU Lesser General Public 
    License along with this software.  If not, see <http://www.gnu.org/licenses/>.

*/

#include "mist.h"

#include <iostream>

#ifdef DEBUG_ON
FILE* f_log = NULL;
QMutex g_log_mutex;

void Write_Log(const char *str, ...){
    QMutexLocker locker(&g_log_mutex);
    va_list arglist;
    char buffer[10240];

    if (!str || !f_log)
    {
        return; 
    }

    va_start(arglist, str);
    vsprintf(buffer, str, arglist);
    va_end(arglist);

    fprintf(f_log, buffer);
    qDebug(buffer);
    fflush(f_log);
}

void Write_Log(QString str){
    QMutexLocker locker(&g_log_mutex);
    if (str.isEmpty() || !f_log)
    {
        return;
    }

    fprintf(f_log, str.toLocal8Bit().data());
    qDebug(str.toLocal8Bit().data());
    fflush(f_log);
}

    #ifdef DEBUG_FUNC_ON
void In_Log(const char *func, QString objectName)
{
    QString str = QString("--->>>") + func;
    Write_Log(QString("\n%1").arg(str, -40) + "(" + objectName + ")\n");
}

void Out_Log(const char *func, QString objectName)
{
    QString str = QString("<<<---") + func;
    Write_Log(QString("%1").arg(str, -40) + "(" + objectName + ")\n");
}
    #endif

void Open_Log(){
    g_log_mutex.lock();
    if ((f_log = fopen(LOG_FILENAME, "w")) == NULL)
    {
        g_log_mutex.unlock();
        return;
    }
    g_log_mutex.unlock();

    Write_Log("CoCon log file\n"
              + QDate::currentDate().toString("yyyy-MM-dd") + " "
              + QTime::currentTime().toString() + "\n");
}

void Close_Log(){
    Write_Log("CoCon end");
    QMutexLocker locker(&g_log_mutex);
    fclose(f_log);
}
#endif  // DEBUG_ON

char* get_exe_path()
{
    static char buff[256];
    char *p;
    int pid;
    pid = getpid();
    sprintf(buff, "/proc/%d/exe", pid);
    readlink(buff, buff, sizeof(buff));
    p = strrchr(buff, '/');
    *p = 0;
    return buff;
}
